﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Net;
using System.Windows.Forms;
using System.Xml.Linq;

namespace gui
{ 
    class WCFClient : IMessageCallback, IDisposable
    {
        string _port;
        string _host;
        string _login;

        ClientSettings _settings = new ClientSettings();

        public event MessageEventHandler OnMessage;
        
        public delegate void MessageEventHandler(string message);


        IMessage pipeProxy = null;
        public NetTcpBinding tcpbinding = new NetTcpBinding();
        public bool Connect()
        {
            Config config = new Config();

            config.GetConfig();
            this._host = config.Ip;
            this._port = config.Port.ToString();
            this._login = config.Login;

            tcpbinding.Security.Mode = SecurityMode.None;
            DuplexChannelFactory<IMessage> pipeFactory =
                  new DuplexChannelFactory<IMessage>(
                      new InstanceContext(this),
                      tcpbinding,
                      new EndpointAddress("net.tcp://"+_host+":"+_port+"/ISubscribe"));

            try
            {
                //открываем канал
                pipeProxy = pipeFactory.CreateChannel();
                //говорим серверу кто подключен
                pipeProxy.Subscribe();
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return false;
            }
        }
        public void Close()
        {
            pipeProxy.Unsubscribe();
        }

        public string SendMessage(string message)
        {
            try
            {
                DateTime dateTime = DateTime.Now;
                string[] stringArrayDateTime = dateTime.ToString().Split(' ');
                string date = stringArrayDateTime[0];
                string time = stringArrayDateTime[1].Split('.')[0];

                XElement xml = new XElement(this._settings.MainElementMessage,
                    new XElement(this._settings.MessageDateElement, date + " " + time),
                    new XElement(this._settings.MessageTextElement, message));

                pipeProxy.AddMessage(xml.ToString());
                return "sent >>>>  " + xml.ToString();
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }

        private void OnMessageChange(string message)
        {
            if (OnMessage != null)
                OnMessage(message);
        }

        //функция вызываемая сервером
        public void OnMessageAdded(string message, DateTime timestamp)
        {
            //DataBase db = new DataBase();

            /*string txt = message + ": " + timestamp.ToString("hh:mm:ss")+"\n";*/

            // Соединяемся с базой
            //db.OpenConnection();

            //Добавляем запись в базу
            //db.CreatData(message, DateTime.Now);

            OnMessageChange(message);
            Console.WriteLine(message + ": " + timestamp.ToString("hh:mm:ss"));
        }

        public void Dispose()
        {
            pipeProxy.Unsubscribe();
        }

    }
}
